import Vue from 'vue'
import Router from 'vue-router'
import Cookie from 'js-cookie'
import store from '../store'
import routes from './routes'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 页面刷新时，重新赋值PCToken
if (Cookie.get('PCToken')) {
  store.dispatch('user/relogin')
}
NProgress.configure({
  showSpinner: true
})
Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: routes
})

// 路由跳转前验证
router.beforeEach((to, from, next) => {
  // 开启进度条
  NProgress.start()
  // 判断页面是有需要登录，若用户未登录则跳转至登录页
  if (to.meta.auth === true) {
    if (!store.state.user.PCToken) {
      router.replace('/login')
    } else {
      store.dispatch('getCategory')
    }
  }
  // 判断是否进入首页， 如果是默认展开分类菜单，否则收起分类菜单
  if (to.path === '/home') {
    store.commit('setMenuStatus', true)
  } else {
    store.commit('setMenuStatus', false)
  }
  next()
})

router.afterEach((to, from) => {
  // 结束进度条
  NProgress.done()
})

export default router
